var uid = -1;
var mid = -1;
var rid = -1;
var countdown = 60; //计时60s
var menuObj = [];
var limit = 15;
layui.use(['table', 'form', 'laydate'], function() {
	var table = layui.table,
		$ = layui.jquery,
		layer = layui.layer,
		form = layui.form,
		laydate = layui.laydate;

	//初始化查询参数
	var options = {
		offset: 0,
		limit: limit,
		pageIndex: 1,
	};
	var userOptions = {
		offset: 0,
		limit: limit,
		pageIndex: 1
	};
	var menuOptions = {
		offset: 0,
		limit: limit,
		pageIndex: 1
	};
	var tempOptions = options;
	var userTempOptions,menuTempOptions;
	loadData(options);

	setTimeout(function () {
		initMenu();
	}, 500);

	$(document).keyup(function(event){
		if(event.keyCode ==13){
			$(".searchTools .search-btn").trigger("click");
		}
	});

	/**搜索角色**/
	$(".searchTools .search-btn").on("click", function() {
		var name = $.trim($(".searchTools .name").val());
		var datas = {
			offset: 0,
			limit: 15,
			pageIndex: 1
		};
		if(!isNull(name) && name != -1)
			datas['name'] = name;
		tempOptions = datas;
		loadData(datas);
	});

	/**搜索用户**/
	$(".userSearchTools .search-btn").on("click", function() {
		var name = $.trim($(".userSearchTools .name").val());
		var datas = {
			offset: 0,
			limit: 15,
			pageIndex: 1,
			rid: rid,
			type: 1
		};
		if(!isNull(name) && name != -1)
			datas['name'] = name;
		userTempOptions = datas;
		loadRelation(datas);
	});

	/**搜索菜单**/
	$(".menuSearchTools .search-btn").on("click", function() {
		var name = $.trim($(".menuSearchTools .name").val());
		var type = $.trim($(".menuSearchTools .type").val());
		var datas = {
			offset: 0,
			limit: 15,
			pageIndex: 1,
			rid: rid,
			type: 2
		};
		if(!isNull(name) && name != -1)
			datas['name'] = name;
		if(!isNull(type) && type != -1)
			datas['menuType'] = parseInt(type);
		menuTempOptions = datas;
		loadRelation(datas);
	});

	//点击添加
	$(".searchTools .add-btn").on("click", function() {
		$(".addModal").show();
	})
	$(".addModal .close").on("click", function() {
		$(".addModal").hide();
		$(".addModal input").val("");
		$(".addModal select").val("");
		$(".addModal textarea").val("");
		form.render();
	})
	//点击添加提交
	form.on('submit(addBtns)', function() {
		var name = $.trim($(".addModal .name").val());
		var roleGroup = $.trim($(".addModal .roleGroup").val());
		var remark = $.trim($(".addModal .remark").val());

		if(isNull(name)) {
			layer.msg("请输入角色名称！");
			return;
		}
		if(isNull(roleGroup)) {
			layer.msg("请输入角色组！");
			return;
		}
		var options = {
			name: name,
			roleGroup: roleGroup
		};
		if(!isNull(remark))
			options['remark'] = remark;

		saveRole(options, "/console/role/save", 0);
	});

	//点击添加提交
	form.on('submit(updateBtns)', function() {
		var name = $.trim($(".updateModal .name").val());
		var roleGroup = $.trim($(".updateModal .roleGroup").val());
		var remark = $.trim($(".updateModal .remark").val());

		if(isNull(name)) {
			layer.msg("请输入角色名称！");
			return;
		}
		if(isNull(roleGroup)) {
			layer.msg("请输入角色组！");
			return;
		}
		var options = {
			id: rid,
			name: name,
			roleGroup: roleGroup
		};
		if(!isNull(remark))
			options['remark'] = remark;

		saveRole(options, "/console/role/update/" + rid, 1);
	});
	//修改按钮
	$(".roleList").on("click", ".set-btn", function() {
		rid = $(this).attr('data-id');
		$(".updateModal .roleGroup").val($(this).attr("data-roleGroup"));
		$(".updateModal .name").val($(this).attr("data-name"));
		$(".updateModal .remark").val($(this).attr("data-remark"));
		$(".updateModal").show();
		form.render();
	});

	//禁用按钮
	$(".roleList").on("click", ".del-btn", function() {
		rid = $(this).attr('data-id');
		var options = {id: rid, status: 1};
		saveRole(options, "/console/role/update/status/" + rid, 3);
	});

	//启用按钮
	$(".roleList").on("click", ".on-btn", function() {
		rid = $(this).attr('data-id');
		var options = {id: rid, status: 0};
		saveRole(options, "/console/role/update/status/" + rid, 3);
	});

	$(".updateModal .close").on("click", function() {
		$(".updateModal").hide();
		$(".updateModal input").val("");
		$(".updateModal select").val("");
		$(".updateModal textarea").val("");
		form.render();
	});

	//点击关联用户
	$(".roleList").on("click", ".user-concat-btn", function() {
		var text = $(this).attr("data-name");
		$(".userModal").show();
		$(".userModal .user-title-msg").html(text + "==>关联用户");
		rid = parseInt($(this).attr("data-id"));
		var userOptions = {
			rid: rid,
			offset: 0,
			limit: limit,
			pageIndex: 1,
			type: 1
		};
		userTempOptions = userOptions;
		/**加载用户信息**/
		loadRelation(userOptions);
	});

	//点击关联菜单
	$(".roleList").on("click", ".menu-concat-btn", function() {
		var text = $(this).attr("data-name");
		$(".menuModal").show();
		$(".menuModal .menu-title-msg").html(text + "==>关联菜单");
		rid = parseInt($(this).attr("data-id"));
		var menuOptions = {
			rid: rid,
			offset: 0,
			limit: limit,
			pageIndex: 1,
			type: 2
		};
		menuTempOptions = menuOptions;
		/**加载用户信息**/
		loadRelation(menuOptions);
	});

	//用户关联角色
	$(".userList").on("click", ".add-concat-btn", function() {
		rid = parseInt($(this).attr("data-rid"));
		uid = parseInt($(this).attr('data-uid'));
		var options = {rid: rid, oid: uid, type: 1, status: 0};
		concatRole(options, "/console/role/update/relation/" + rid);
	});
	//菜单关联角色
	$(".menuList").on("click", ".add-concat-btn", function() {
		rid = parseInt($(this).attr("data-rid"));
		mid = parseInt($(this).attr('data-mid'));
		var options = {rid: rid, oid: mid, type: 2, status: 0};
		concatRole(options, "/console/role/update/relation/" + rid);
	});

	//用户取消关联角色
	$(".userList").on("click", ".delete-concat-btn", function() {
		rid = parseInt($(this).attr("data-rid"));
		uid = parseInt($(this).attr('data-uid'));
		var options = {rid: rid, oid: uid, type: 1, status: 1};
		concatRole(options, "/console/role/update/relation/" + rid);
	});
	//菜单取消关联角色
	$(".menuList").on("click", ".delete-concat-btn", function() {
		rid = parseInt($(this).attr("data-rid"));
		mid = parseInt($(this).attr('data-mid'));
		var options = {rid: rid, oid: mid, type: 2, status: 1};
		concatRole(options, "/console/role/update/relation/" + rid);
	});

	/**关闭关联弹出框**/
	$(".menuModal .close").on("click", function() {
		$(".menuModal").hide();
	});

	/**关闭关联按钮弹出框**/
	$(".userModal .close").on("click", function() {
		$(".userModal").hide();
	});

	//获取数据列表
	function loadData(options) {
		var loading = layer.load(1);
		$.ajax({
			type: "POST",
			url: "/console/role/list",
			async: true,
			dataType: 'json',
			timeout: 30000,
			data: options,
			success: function(res) {
				layer.close(loading);
								// console.log(res);
				if(res.code == 0) {
					$(".roleListPage").page({
						total: res.data.total, //总条数
						pageIndex: options.pageIndex, //当前页
						pageSize: options.limit, //每页显示
						showInfo: true, //是否显示记录信息
						prevBtnText: '上一页',
						nextBtnText: "下一页",
						infoFormat: '总共{total}条记录,每页显示{size}条记录,共{count}页' //定义记录信息格式
					}).on("pageClicked", function(event, pageIndex) {
						//分页点击
						options.offset = options.offset - (options.pageIndex-pageIndex )* options.limit;
						options.pageIndex = pageIndex;
						loadData(options);
					});

					//具体数据列表
					var data = res.data.records;
					if(data == null || data.length <= 0) {
						$(".roleList .tableList").empty().append("<tr><td colspan='5'>暂无数据</td></tr>");
						return;
					}
					var html = '';
					$.each(data, function(index, val) {
						var statusBtn = '';
						var btn = '';
						if (val.status == 0)
							statusBtn = '<a href="javascript:void(0)" data-id="' + val.id + '" class="layui-btn del-btn" style="background-color:#d9534f"><img src="/static/console/img/off.png" />禁用</a>';
						else
							statusBtn = '<a href="javascript:void(0)" data-id="' + val.id + '" class="layui-btn on-btn" style="background-color:#5FB878"><img src="/static/console/img/on.png" />启用</a>';
						var userConcatBtn = '<a href="javascript:void(0)" data-name="' + val.name + '" data-id="' + val.id + '" class="layui-btn user-concat-btn" style="background-color:#1890ff"><img src="/static/console/img/concat.png" />关联员工</a>';
						var menuConcatBtn = '<a href="javascript:void(0)" data-name="' + val.name + '" data-id="' + val.id + '" class="layui-btn menu-concat-btn" style="background-color:#1890ff"><img src="/static/console/img/concat.png" />关联菜单</a>';
						var statusStr = val.status == 0 ? '正常' : '禁用';
						var btn = '<a href="javascript:void(0)" data-roleGroup="' + val.roleGroup + '" data-name="' + val.name + '" data-id="' + val.id
							+ '" data-remark="' + val.remark + '" class="layui-btn set-btn" style="background-color:#1890ff">' +
							'<img src="/static/console/img/edit.png" />修改</a>' + statusBtn + userConcatBtn + menuConcatBtn;
						html += "<tr><td>" + val.name + "</td><td>" + val.roleGroup + "</td><td>" + statusStr + "</td>" +
							"<td>" + val.remark + "</td><td>" + btn + "</td></tr>";
					});
					$(".roleList .tableList").empty().append(html);
					replaceNull($(".roleList .tableList"));
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}
			}
		});
	}

	/**加载按钮信息**/
	function concatRole(options, url) {
		var loading = layer.load(1);
		$.ajax({
			type: "put",
			url: url,
			async: true,
			dataType: 'json',
			timeout: 30000,
			data: options,
			success: function(res) {
				layer.close(loading);
				if(res.code == 0) {
					// console.log(res.data)
					if (options.type == 1)
						loadRelation(userTempOptions);
					else if (options.type == 2)
						loadRelation(menuTempOptions)
					// loadButtonData(res.data);
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	/**组装按钮HTML**/
	function loadUserRelationData(data) {
		if(data == null || data.length <= 0) {
			$(".userList .tableList").empty().append("<tr><td colspan='4'>暂无数据</td></tr>");
			return;
		}
		var html = '';
		$.each(data, function(index, val) {
			var statusText = "";
			var btn = "";
			if (val.status == 0) {
				statusText = '已关联';
				btn = "<a href='javascript:void(0)' data-uid='" + val.id + "' data-rid='" + rid + "' class='layui-btn delete-concat-btn'>删除关联</a>";
			} else {
				btn = "<a href='javascript:void(0)' data-uid='" + val.id + "' data-rid='" + rid + "' class='layui-btn add-concat-btn'>添加关联</a>";
			}
			html += "<tr><td>" + val.username + "</td><td>" + val.name +
				"</td><td>" + statusText + "</td><td>" + btn + "</td></tr>";
		});
		$(".userList .tableList").empty().append(html);
		replaceNull($(".userList .tableList"));
	}

	/**组装按钮HTML**/
	function loadMenuRelationData(data) {
		if(data == null || data.length <= 0) {
			$(".menuList .tableList").empty().append("<tr><td colspan='5'>暂无数据</td></tr>");
			return;
		}
		var html = '';
		$.each(data, function(index, val) {
			var statusText = "";
			var btn = "";
			var type = '手机';
			if (val.type == 0)
				type = '手机';
			else if (val.type == 1)
				type = '后台';
			else if (val.type == 2)
				type = 'URL';

			if (val.status == 0) {
				statusText = '已关联';
				btn = "<a href='javascript:void(0)' data-mid='" + val.id + "' data-rid='" + rid + "' class='layui-btn delete-concat-btn'>删除关联</a>";
			} else {
				btn = "<a href='javascript:void(0)' data-mid='" + val.id + "' data-rid='" + rid + "' class='layui-btn add-concat-btn'>添加关联</a>";
			}
			html += "<tr><td>" + val.name + "</td><td>" + convertVal(menuObj[val.pid]) +
				"</td><td>" + type + "</td><td>" + statusText + "</td><td>" + btn + "</td></tr>";
		});
		$(".menuList .tableList").empty().append(html);
		replaceNull($(".menuList .tableList"));
	}


	//获取父级资源
	function initMenu() {
		var loading = layer.load(1);
		$.ajax({
			type: "post",
			url: "/sys_menu/list",
			async: true,
			dataType: 'json',
			timeout: 30000,
			data: {
				limit: 1000,
				pageIndex: 1,
				offset: 0
			},
			success: function(res) {
				layer.close(loading);
				if(res.code == 0) {
					var datas = res.data.records;
					var html = "<option value='-1'></option>";
					$.each(datas, function(i, v) {
						var type = '手机';
						if (v.type == 0)
							type = '手机';
						else if (v.type == 1)
							type = '后台';
						else if (v.type == 2)
							type = 'URL';
						menuObj[v.id] = v.name + "(" + type + ")";
					})
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	//获取用户列表
	function loadRelation(options) {
		var loading = layer.load(1);
		$.ajax({
			type: "POST",
			url: "/console/role/query/relation",
			async: true,
			dataType: 'json',
			timeout: 30000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					if (options.type == 1) {
						$(".userListPage").page({
							total: res.data.total, //总条数
							pageIndex: options.pageIndex, //当前页
							pageSize: options.limit, //每页显示
							showInfo: true, //是否显示记录信息
							prevBtnText: '上一页',
							nextBtnText: "下一页",
							infoFormat: '总共{total}条记录,每页显示{size}条记录,共{count}页' //定义记录信息格式
						}).on("pageClicked", function(event, pageIndex) {
							//分页点击
							options.offset = options.offset - (options.pageIndex-pageIndex )* options.limit;
							options.pageIndex = pageIndex;
							loadRelation(options);
						});
						loadUserRelationData(res.data.data);
					} else if (options.type == 2) {
						$(".menuListPage").page({
							total: res.data.total, //总条数
							pageIndex: options.pageIndex, //当前页
							pageSize: options.limit, //每页显示
							showInfo: true, //是否显示记录信息
							prevBtnText: '上一页',
							nextBtnText: "下一页",
							infoFormat: '总共{total}条记录,每页显示{size}条记录,共{count}页' //定义记录信息格式
						}).on("pageClicked", function(event, pageIndex) {
							//分页点击
							options.offset = options.offset - (options.pageIndex-pageIndex )* options.limit;
							options.pageIndex = pageIndex;
							loadRelation(options);
						});
						loadMenuRelationData(res.data.data);
					}
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});

	}

	/**保存角色信息**/
	function saveRole(options, url, type) {
		var loading = layer.load(1);
		$.ajax({
			type: "put",
			url: url,
			async: true,
			dataType: 'json',
			timeout: 30000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					if (type == 0) {
						$(".addModal").hide();
						$(".addModal input").val("");
						$(".addModal select").val("");
						$(".addModal textarea").val("");
					} else if (type == 1) {
						$(".updateModal").hide();
						$(".updateModal input").val("");
						$(".updateModal select").val("");
						$(".updateModal textarea").val("");
					}
					layer.msg(res.msg);
					form.render();
					loadData(tempOptions);
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	/**显示值转换**/
	function convertVal(val) {
		if (val == null || val == '' || val == undefined)
			return '';
		else
			return val;
	}
	
});